let util = require('../../utils/util');

let requestDomain = util.config('requestDomain');

let that;

Page({

  data: {

    finding: false,

    mode: '',

    newServiceName: '',

    editServiceId: '',
  
    serviceList: [],

    addServiceDisabled: false

  },

  onLoad: function (options) {
  
    that = this;

    that.getServiceList();

  },

  serviceItemClick: function(e) {
    let funId = e.currentTarget.dataset.serviceid;
    let {mode} = that.data;
    if(mode == 'add' || mode == 'edit') {
        return;
    }
    if(!funId || funId == '') {
        wx.showModal({
            title: '提示',
            content: '此服务无效，请重新选择'
        });
        return;
    }
    wx.showActionSheet({
        itemList: ['修改', '删除', '上移', '下移'],
        success: function(result) {
            switch (result.tapIndex) {
                case 0:
                    that.setData({
                        mode: 'edit',
                        editServiceId: funId
                    });
                break;
                case 1: 
                    that.delService(funId);
                break;
                case 2:
                    that.upService(funId);
                break;
                case 3:
                    that.downService(funId);
                break;
            }
        }
    })
  },

  newServiceNameInput: function(e) {
    that.data.newServiceName = e.detail.value;
  },

  getServiceList: function() {
      wx.showNavigationBarLoading();
      wx.showToast({
          title: '获取中',
          icon: 'loading',
          duration: 10000,
          mask: true
      });
      that.setData({finding: true});
      wx.request({
          url: requestDomain + 'service/find',
          method: 'POST',
          data: {
            storeId: util.globalData('storeId'),
            _3rdSession: util.globalData('_3rdSession')
          },
          success: function(result) {
            wx.hideNavigationBarLoading();
            wx.hideToast();
            that.setData({ finding: false });
            if(util.checkSuccess(result) && result.data && result.data.data) {
                //将服务列表按序号正序排序
                let serviceList = result.data.data.sort(function(a, b) {
                    return a.funSid - b.funSid;
                });
                let temp = [];
                for (let serviceIndex in serviceList) {
                    serviceList[serviceIndex].funSid = parseInt(serviceIndex) + 1;
                    temp.push(serviceList[serviceIndex]);
                }
                serviceList = temp;
                that.setData({serviceList: serviceList});
            }
            else {
                util.showError('获取失败', '获取服务列表失败' + result.data.errMsg, result.data.errCode);
            }
            wx.stopPullDownRefresh();
          },
          fail: function() {
              wx.hideNavigationBarLoading();
              wx.hideToast();
              wx.stopPullDownRefresh();
              that.setData({ finding: false });
              util.showError('获取失败', '发送获取服务列表请求失败');
          }
      })
  },

  preAddService: function() {
    that.setData({
        mode: 'add'
    });
  },

  addService: function() {
    let {serviceList, newServiceName} = that.data;
    if (newServiceName.replace(/(^\s*)|(\s*$)/g, '') == '') {
        wx.showModal({
            title: '提示',
            content: '请填写需要新增的服务名称'
        });
        return;
    }
    that.setData({ addServiceDisabled: true });
    wx.showNavigationBarLoading();
    wx.request({
        url: requestDomain + 'service/add',
        method: 'POST',
        data: {
            storeId: util.globalData('storeId'),
            _3rdSession: util.globalData('_3rdSession'),
            funSid: serviceList.length + 1,
            funName: newServiceName
        },
        success: function(result) {
            wx.hideNavigationBarLoading();
            that.setData({ addServiceDisabled: false });
            if(util.checkSuccess(result) && result.data && result.data.data) {
                let {funId} = result.data.data;
                serviceList.push({
                    funSid: serviceList.length + 1,
                    funId: funId,
                    funName: newServiceName,
                });
                that.setData({
                    mode: '',
                    newServiceName: '',
                    serviceList: serviceList
                });
                wx.showToast({
                    title: '添加成功',
                    icon: 'success'
                });
            }
            else {
                util.showError('添加失败', '添加服务时发生错误' + result.data.errMsg, result.data.errCode);
            }
        },
        fail: function() {
            wx.hideNavigationBarLoading();
            that.setData({ addServiceDisabled: false });
            util.showError('添加失败', '发起添加服务请求失败');
        }
    });
  },

  cancelUseService: function() {
    that.setData({mode: ''});
  },

  editService: function() {
    wx.showModal({
        title: '确认修改？',
        content: '确认要修改此项服务的名称吗',
        success: function(modal) {
            if(modal.confirm) {
                let {editServiceId, newServiceName, serviceList} = that.data;
                wx.showNavigationBarLoading();
                wx.request({
                    url: requestDomain + 'service/update',
                    method: 'POST',
                    data: {
                        storeId: util.globalData('storeId'),
                        _3rdSession: util.globalData('_3rdSession'),
                        funId: editServiceId,
                        funName: newServiceName
                    },
                    success: function(result) {
                        wx.hideNavigationBarLoading();
                        if(util.checkSuccess(result)) {
                            for(let serviceIndex in serviceList) {
                                if (serviceList[serviceIndex].funId == editServiceId) {
                                    serviceList[serviceIndex].funName = newServiceName;
                                    break;
                                }
                            }
                            that.setData({
                                mode: '',
                                editServiceId: '',
                                newServiceName: '',
                                serviceList: serviceList
                            });
                        }
                        else {
                            util.showError('修改失败', '修改服务名称时出现错误' + result.data.errMsg, result.data.errCode);
                        }
                    },
                    fail: function() {
                        util.showError('修改失败', '发起修改服务名称请求失败');
                    }
                })
            }
        }
    });
  },

  delService: function (funId) {
    wx.showModal({
        title: '确认删除？',
        content: '确认要删除此项服务吗？',
        success: function(modal) {
            if(modal.confirm) {
                wx.showNavigationBarLoading();
                wx.request({
                    url: requestDomain + 'service/del',
                    method: 'POST',
                    data: {
                        storeId: util.globalData('storeId'),
                        _3rdSession: util.globalData('_3rdSession'),
                        funId: funId
                    },
                    success: function(result) {
                        wx.hideNavigationBarLoading();
                        if(util.checkSuccess(result)) {
                            let {serviceList} = that.data;
                            for (let serviceIndex in serviceList) {
                                if (serviceList[serviceIndex].funId == funId) {
                                    serviceList.splice(serviceIndex, 1);
                                    for (let i = serviceIndex;i < serviceList.length;i++) {
                                        serviceList[i].funSid = parseInt(i) + 1;
                                    }
                                    break;
                                }
                            }
                            that.setData({ serviceList: serviceList });
                            wx.showToast({
                                title: '删除成功',
                                icon: 'success'
                            });
                        }
                        else {
                            util.showError('删除失败', '删除服务时发生错误' + result.data.errMsg, result.data.errCode);
                        }
                    },
                    fail: function() {
                        wx.hideNavigationBarLoading();
                        util.showError('删除失败', '发起删除服务请求失败');
                    }
                })
            }
        }
    });
  },

  upService: function(funId) {
    let {serviceList} = that.data;
    let requestData = {
        storeId: util.globalData('storeId'),
        _3rdSession: util.globalData('_3rdSession'),
        funId1: '',
        funId2: '',
        funSid1: '',
        funSid2: ''
    };
    for(let serviceIndex in serviceList) {
        serviceIndex = parseInt(serviceIndex);
        if (serviceList[serviceIndex].funId == funId && serviceIndex != 0) {
            let temp = serviceList[serviceIndex];
            serviceList[serviceIndex] = serviceList[serviceIndex - 1];
            serviceList[serviceIndex - 1] = temp;
            serviceList[serviceIndex].funSid++;
            serviceList[serviceIndex - 1].funSid--;
            requestData.funId1 = serviceList[serviceIndex].funId;
            requestData.funId2 = serviceList[serviceIndex - 1].funId;
            requestData.funSid1 = serviceList[serviceIndex].funSid;
            requestData.funSid2 = serviceList[serviceIndex - 1].funSid;
            break;
        }
    }
    if (requestData.funId1 == '') {
        return;
    }
    wx.showNavigationBarLoading();
    wx.request({
        url: requestDomain + 'service/up',
        method: 'POST',
        data: requestData,
        success: function (result) {
            wx.hideNavigationBarLoading();
            if (util.checkSuccess(result)) {
                wx.showToast({
                    title: '上移成功',
                    icon: 'success'
                });
                that.setData({ serviceList: serviceList });
            }
            else {
                util.showError('上移失败', '上移服务时出现错误' + result.data.errMsg, result.data.errCode);
            }
        },
        fail: function () {
            util.showError('上移失败', '发起服务上移请求失败');
        }
    });
  },

  downService: function(funId) {
    let {serviceList} = that.data;
    let requestData = {
        storeId: util.globalData('storeId'),
        _3rdSession: util.globalData('_3rdSession'),
        funId1: '',
        funId2: '',
        funSid1: '',
        funSid2: ''
    };
    for (let serviceIndex in serviceList) {
        serviceIndex = parseInt(serviceIndex);
        if (serviceList[serviceIndex].funId == funId && serviceIndex != serviceList.length - 1) {
            let temp = serviceList[serviceIndex];
            serviceList[serviceIndex] = serviceList[serviceIndex + 1];
            serviceList[serviceIndex + 1] = temp;
            serviceList[serviceIndex].funSid--;
            serviceList[serviceIndex + 1].funSid++;
            requestData.funId1 = serviceList[serviceIndex].funId;
            requestData.funId2 = serviceList[serviceIndex + 1].funId;
            requestData.funSid1 = serviceList[serviceIndex].funSid;
            requestData.funSid2 = serviceList[serviceIndex + 1].funSid;
            break;
        }
    }
    if (requestData.funId1 == '') {
        return;
    }
    wx.showNavigationBarLoading();
    wx.request({
        url: requestDomain + 'service/down',
        method: 'POST',
        data: requestData,
        success: function(result) {
            wx.hideNavigationBarLoading();
            if(util.checkSuccess(result)) {
                wx.showToast({
                    title: '下移成功',
                    icon: 'success'
                });
                that.setData({ serviceList: serviceList });
            }
            else {
                util.showError('下移失败', '下移服务时出现错误' + result.data.errMsg, result.data.errCode);
            }
        },
        fail: function() {
            util.showError('下移失败', '发起服务下移请求失败');
        }
    });
  },

  onPullDownRefresh: function() {
      that.getServiceList();
  }

});